package com.information.manage.gyjc.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.information.manage.basic.common.result.Result;
import com.information.manage.basic.common.token.TokenUtils;
import com.information.manage.basic.mapper.StaffMapper;
import com.information.manage.basic.mapper.SysRelUserStaffMapper;
import com.information.manage.basic.model.entity.StaffDO;
import com.information.manage.basic.model.entity.SysRelUserStaffDO;
import com.information.manage.gyjc.mapper.*;
import com.information.manage.gyjc.model.dto.InspectRecordDto;
import com.information.manage.gyjc.model.enity.*;
import com.information.manage.gyjc.model.query.InspectRecordQuery;
import com.information.manage.gyjc.model.vo.InspectRecordPage;
import com.information.manage.gyjc.model.vo.InspectRecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.SpringServletContainerInitializer;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/gyjc/inspect_record")
public class InspectRecordController {
    @Autowired
    private InspectRecordMapper inspectRecordMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private GongzzMapper gongzzMapper;
    @Autowired
    private StaffMapper staffMapper;
    @Autowired
    private RefGyGxMapper refGyGxMapper;
    @Autowired
    private GongxuMapper gongxuMapper;
    @Autowired
    private GongyiMapper gongyiMapper;
    @Autowired
    private SysRelUserStaffMapper sysRelUserStaffMapper;

    // 查询所有巡检记录
    @PostMapping("/list")
    public Result inspectRecordList(@RequestBody InspectRecordQuery inspectRecordQuery) {
        List<InspectRecordVo> recordVoList = new ArrayList<>();
        InspectRecordPage result = new InspectRecordPage();
        Page<InspectRecord> page = new Page<>(inspectRecordQuery.getCurPage(), inspectRecordQuery.getSize());
        QueryWrapper<InspectRecord> wrapper = new QueryWrapper<>();
        if (inspectRecordQuery.getZnumber() != null) {
            wrapper.eq("gzz_id", inspectRecordQuery.getZnumber());
        }
        if (inspectRecordQuery.getPname() != null) {
            List<Product> productList = productMapper
                    .selectList(new QueryWrapper<Product>().like("pname", inspectRecordQuery.getPname()));
            if (!productList.isEmpty()) {
                ArrayList<Integer> arrayList = new ArrayList<>();
                for (Product product : productList) {
                    arrayList.add(product.getId());
                }
                wrapper.in("p_id", arrayList);
            } else {
                return Result.fail("没有查询到相关产品");
            }
        }
        if (inspectRecordQuery.getStaffName() != null) {
            List<StaffDO> staffList = staffMapper.selectList(new QueryWrapper<StaffDO>().like("name", inspectRecordQuery.getStaffName()));
            if (!staffList.isEmpty()) {
                ArrayList<Integer> arrayList = new ArrayList<>();
                for (StaffDO staff : staffList) {
                    arrayList.add(staff.getId());
                }
                wrapper.in("oprater_id", arrayList);
            } else {
                return Result.fail("没有查询到相关员工");
            }
        }


        Page<InspectRecord> recordPage = inspectRecordMapper.selectPage(page, wrapper);
        List<InspectRecord> recordList = recordPage.getRecords();
        result.setCurrent((int) recordPage.getCurrent());
        result.setPages((int) recordPage.getPages());
        result.setSize((int) recordPage.getSize());
        result.setTotal((int) recordPage.getTotal());

        recordList.forEach(item ->

        {
            InspectRecordVo recordVo = new InspectRecordVo();
            recordVo.setInspectRecord(item);
            recordVo.setProduct(productMapper.selectById(item.getPid()));
            recordVo.setGongzz(gongzzMapper.selectById(item.getGzzId()));
            recordVo.setStaff(staffMapper.selectById(item.getOpraterId()));
            recordVoList.add(recordVo);
        });
        result.setRecords(recordVoList);
        return Result.ok(result);
    }

    // 根据ID巡检记录
    @GetMapping("/select/{id}")
    public Result<InspectRecordVo> inspectRecordById(@PathVariable Integer id) {
        InspectRecordVo recordVo = new InspectRecordVo();
        InspectRecord record = inspectRecordMapper.selectById(id);
        recordVo.setInspectRecord(record);
        recordVo.setProduct(productMapper.selectById(record.getPid()));
        recordVo.setGongzz(gongzzMapper.selectById(record.getGzzId()));
        recordVo.setStaff(staffMapper.selectById(record.getOpraterId()));
        return Result.ok(recordVo);
    }

    // 修改巡检记录
    @PostMapping("/update")
    public Result<String> updateInspectRecord(@RequestBody InspectRecord inspectRecord) {
        int res = inspectRecordMapper.updateById(inspectRecord);
        return Result.ok(res > 0 ? "修改成功" : "修改失败");
    }

    // 添加巡检记录
    @PostMapping("/add")
    public Result<String> addInspectRecord(@RequestBody InspectRecordDto inspectRecord, @RequestHeader String token) {
        System.out.println("token: " + token);
        Integer id = TokenUtils.getUserId(token);
        SysRelUserStaffDO rel = sysRelUserStaffMapper.selectOne(new QueryWrapper<SysRelUserStaffDO>().eq("user_id", id));


        InspectRecord one = inspectRecordMapper.selectOne(new QueryWrapper<InspectRecord>()
                .eq("pnumber", inspectRecord.getPnumber())
                .eq("gx_id", inspectRecord.getGxId()));
        if (one != null) {
            return Result.fail("该产品已有这个工序的巡检记录");
        }

        Product product = productMapper.selectOne(new QueryWrapper<Product>().eq("pno", inspectRecord.getPno()));
        if (product == null) {
            return Result.fail("没有查询到相关产品");
        }
        Gongyi gongyi = gongyiMapper.selectById(product.getGyId());
        if (gongyi == null) {
            return Result.fail("没有查询到相关工艺");
        }
        RefGyGx refGyGx = refGyGxMapper.selectOne(new QueryWrapper<RefGyGx>()
                .eq("gy_id", gongyi.getId())
                .eq("gx_id", inspectRecord.getGxId()));
        if (refGyGx == null) {
            return Result.fail("没有查询到相关工艺与工序关系");
        }
        if (refGyGx.getGxOrder() == 1) {
            return getRecordResult(inspectRecord, product, rel.getStaffId());
        }
//        RefGyGx refGyGxAfter = refGyGxMapper.selectOne(new QueryWrapper<RefGyGx>()
//                .eq("gy_id", gongyi.getId())
//                .eq("gx_order", refGyGx.getGxOrder() + 1));
//        if (refGyGxAfter == null) {
//            return Result.fail("该工序为最后一工序，不能再添加巡检记录");
//        }
        RefGyGx refGyGxBefore = refGyGxMapper.selectOne(new QueryWrapper<RefGyGx>()
                .eq("gy_id", gongyi.getId())
                .eq("gx_order", refGyGx.getGxOrder() - 1));

        InspectRecord recordBefore = inspectRecordMapper.selectOne(new QueryWrapper<InspectRecord>()
                .eq("pnumber", inspectRecord.getPnumber())
                .eq("gx_id", refGyGxBefore.getGxId()));
        if (recordBefore == null) {
            return Result.fail("该产品没有上一工序的巡检记录");
        }
        if (recordBefore.getIspass() == 0) {
            return Result.fail("上一工序的巡检记录未通过，不能再添加下一工序的巡检记录");
        }
        return getRecordResult(inspectRecord, product, rel.getStaffId());
    }

    private Result<String> getRecordResult(InspectRecordDto inspectRecord, Product product, Integer staffId) {
        InspectRecord record = new InspectRecord();
        record.setPnumber(inspectRecord.getPnumber());
        record.setPid(product.getId());
        record.setGzzId(inspectRecord.getGzzId());
        record.setOpraterId(staffId);
        record.setInsvalue(inspectRecord.getInsvalue());
        record.setInsunit(product.getPunit());
        record.setGxId(inspectRecord.getGxId());
        Gongxu gongxu = gongxuMapper.selectById(inspectRecord.getGxId());
        if (gongxu == null) {
            return Result.fail("没有查询到相关工序");
        }
        if (gongxu.getIscheck() == 1) {
            switch (gongxu.getCheckrule()) {
                // 等于值
                case 0: {
                    if (inspectRecord.getInsvalue() == gongxu.getJcvalue()) {
                        record.setIspass(1);
                        break;
                    }
                    record.setIspass(0);
                    break;
                }
                // 大于值
                case 1: {
                    if (inspectRecord.getInsvalue() > gongxu.getJcvalue()) {
                        record.setIspass(1);
                        break;
                    }
                    record.setIspass(0);
                    break;
                }
                // 大于等于值
                case 2: {
                    if (inspectRecord.getInsvalue() >= gongxu.getJcvalue()) {
                        record.setIspass(1);
                        break;
                    }
                    record.setIspass(0);
                    break;
                }
                // 小于值
                case -1: {
                    if (inspectRecord.getInsvalue() < gongxu.getJcvalue()) {
                        record.setIspass(1);
                        break;
                    }
                    record.setIspass(0);
                    break;
                }
                // 小于等于值
                case -2: {
                    if (inspectRecord.getInsvalue() <= gongxu.getJcvalue()) {
                        record.setIspass(1);
                        break;
                    }
                    record.setIspass(0);
                    break;
                }
                default: {
                    record.setIspass(0);
                    break;
                }
            }
            record.setRemark(inspectRecord.getRemark());
        } else {
            record.setIspass(1);
        }
        int res = inspectRecordMapper.insert(record);
        return Result.ok(res > 0 ? "添加成功" : "添加失败");
    }



    // 删除巡检记录
    @DeleteMapping("/delete/{id}")
    public Result<String> deleteInspectRecord(@PathVariable Integer id) {
        int res = inspectRecordMapper.deleteById(id);
        return Result.ok(res > 0 ? "删除成功" : "删除失败");
    }

}
